package com.newgoldcurrency.activities;

import android.os.Bundle;
import android.os.SystemClock;

import androidx.appcompat.app.AppCompatActivity;

import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.adapter.ChatAdapter;
import com.newgoldcurrency.bean.ChatBean;
import com.newgoldcurrency.databinding.ActivityChatBinding;
import com.newgoldcurrency.utils.NettyClient;
import com.newgoldcurrency.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity {
    private ActivityChatBinding binding;
    private ChatAdapter adp;
    private final List<ChatBean> data = new ArrayList<>();
    private NettyClient nettyClient;
    private long mClickTime;
    private boolean isFirst=true;

    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityChatBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.chatBack.setOnClickListener(v -> finish());
        adp = new ChatAdapter(this, data);
        binding.chatList.setAdapter(adp);
        binding.chatSend.setOnClickListener(v -> {
           if (checkDoubleClick()){
               String content = binding.chatEt.getText().toString();
               if (content.equals("")){
                   Tools.toast(getString(R.string.input_content));
                   return;
               }
               binding.chatEt.setText("");
               data.add(new ChatBean("right", content, new Date().toString()));
               try {
                   //发送出去
                   JSONObject jo = new JSONObject();
                   jo.put("from", App.userBean.id);
                   jo.put("msg", content);
                   jo.put("cmd", "MESSAGE");
                   jo.put("to", getIntent().getStringExtra("id"));
                   nettyClient.sendMsg(jo);
                   //加入本地数据库
                   App.sql.addUnread(content, App.userBean.id, getIntent().getStringExtra("id"), String.valueOf(System.currentTimeMillis()));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
               notifyData();
               binding.chatList.setSelection(data.size() - 1);
           }
        });
        binding.chatCode.setText(getIntent().getStringExtra("code"));
        binding.chatClear.setOnClickListener(v -> Tools.dialog(ChatActivity.this, "Tips", getString(R.string.delete_chat_history), "Confirm", "Cancel", v1 -> {
            App.sql.delete(App.userBean.id, getIntent().getStringExtra("id"));
            data.clear();
            adp.notifyDataSetChanged();
        }));
        nettyClient = new NettyClient(jo -> runOnUiThread(() -> {
            String cmd = jo.get("cmd").getAsString();
            switch (cmd) {
                case "CONNECT":
                    if (isFirst){
                        getSingleMsg();
                        isFirst=false;
                    }
                    break;
                case "GET_SINGLE_MSG":
                    JSONArray ja = App.sql.addUnreads(true, jo.get("msg").getAsJsonArray(), getIntent().getStringExtra("id"), App.userBean.id);
                    for (int i = 0; i < ja.length(); i++) {
                        try {
                            JSONObject j = ja.getJSONObject(i);
                            j.getString("objectId");
                            j.getString("toId");
                            j.getString("fromId");
                            j.getString("timestamp");
                            j.getString("content");
                            if (j.getString("toId").equals(App.userBean.id)) {
                                data.add(new ChatBean("left", j.getString("content"), j.getString("timestamp")));
                            } else {
                                data.add(new ChatBean("right", j.getString("content"), j.getString("timestamp")));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                       notifyData();
                    }
                    break;
                case "MESSAGE":
                    data.add(new ChatBean("left", jo.get("msg").getAsString(), jo.get("create_time").getAsString()));
                    notifyData();
                    App.sql.addUnread(jo.get("msg").getAsString(), getIntent().getStringExtra("id"), App.userBean.id, jo.get("create_time").getAsString());
                    break;
            }
        }));
    }
    public void notifyData(){
        adp.notifyDataSetChanged();
        binding.chatList.setSelection(data.size() - 1);
    }
    private void getSingleMsg() {
        try {
            JSONObject jo1 = new JSONObject();
            jo1.put("cmd", "GET_SINGLE_MSG");
            jo1.put("from", getIntent().getStringExtra("id"));
            jo1.put("user_id", getIntent().getStringExtra("mineId"));
            nettyClient.sendMsg(jo1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        nettyClient.start("CHAT");
    }

    @Override
    protected void onPause() {
        super.onPause();
        nettyClient.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding=null;
    }
}